import React from 'react';
import { Link } from 'react-router-dom';
import PropTypes from 'prop-types';

import { Carousel, message } from 'antd';
import { inject, observer } from 'mobx-react';

import NewsList from '../store/new_list'

@inject((stores) => {
  const store = {
    newsList: stores.newsList,
  }
  return store
})
@observer
class Slider extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
    }
  }
  componentDidMount() {
    if (!this.props.imgList || !this.props.imgList.length) { this.getNews(); }
  }
  // 请求数据
  getNews() {
    // 获取新参数，channel和num
    const { type, count } = this.props;
    this.props.newsList.getSliderNews(type, count).catch(e => message.error(`出错了${e}`))
  }
  asyncBootstrap() {
    if (!this.props.imgList || !this.props.imgList.length) {
      return new Promise((resolve, reject) => {
        const { type, count } = this.props;
        this.props.newsList.getImageNews(type, count)
          .then(() => resolve(true)).catch(reject)
      })
    }
    return true
  }
  render() {
    const setting = this.props.setting || {
      autoplay: true,
      speed: 500,
    }
    const newsSliderData = this.props.newsList.newsSliderData.get(this.props.type);
    const imgList = newsSliderData ? newsSliderData.data || [] : this.props.imgList || []
    return (
      <div className="slider">
        <Carousel {...setting}>
          { imgList ? imgList.map(imgItem => (
            <div key={imgItem.id}>
              <Link to={`/detail/${imgItem.id}`} className="slider-img">
                <img src={imgItem.pic} alt={imgItem.title} />
              </Link>
              <h3 className="img-title">
                <Link to={`/detail/${imgItem.id}`}>{imgItem.title}</Link>
              </h3>
            </div>)) : null
          }
        </Carousel>
      </div>
    )
  }
}
export default Slider;
Slider.propTypes = {
  imgList: PropTypes.arrayOf(Object),
  setting: PropTypes.objectOf(Object),
  type: PropTypes.string,
  count: PropTypes.string,
  newsList: PropTypes.instanceOf(NewsList),
}

